import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 用定时器模拟异步请求
export const fetchPosts = createAsyncThunk(
  'posts/fetchPosts',
  async () => {
    // 模拟网络延迟（1秒后返回数据）
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟从服务器获取的数据
        const mockData = [
          { id: 1, title: '模拟数据 1' },
          { id: 2, title: '模拟数据 2' },
          { id: 3, title: '模拟数据 3' }
        ];
        resolve(mockData); // 成功返回数据（会作为 fulfilled 的 payload）
      }, 1000); // 1秒延迟
    });
  }
);

// 模拟失败的情况（可选）
export const fetchPostsWithError = createAsyncThunk(
  'posts/fetchPostsWithError',
  async () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟请求失败
        reject(new Error('模拟请求失败：网络错误'));
      }, 1000);
    });
  }
);

const postsSlice = createSlice({
  name: 'posts',
  initialState: {
    data: [],
    status: 'idle', // idle / loading / succeeded / failed
    error: null
  },
  extraReducers: (builder) => {
    builder
      // 处理成功的异步请求
      .addCase(fetchPosts.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchPosts.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.data = action.payload; // 接收模拟的数据源
      })
      .addCase(fetchPosts.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      })
      // 处理失败的异步请求（可选）
      .addCase(fetchPostsWithError.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      });
  }
});

export default postsSlice.reducer;
